<template>
  <el-dialog
    :title="id ? 'Update' : 'Insert'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="onClose"
  >
    <el-form
      ref="formEle"
      label-width="150px"
      v-loading="isLoadingAdminInfo"
      :model="adminForm"
      :rules="adminFormRules"
      :validate-on-rule-change="false"
      @submit.prevent="handleSubmit"
    >
      <el-form-item label="Account" prop="account">
        <el-input v-model="adminForm.account"></el-input>
      </el-form-item>
      <el-form-item label="Password" prop="pwd">
        <el-input v-model="adminForm.pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="Confirm password" prop="conf_pwd">
        <el-input v-model="adminForm.conf_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="Role" prop="roles">
        <el-checkbox-group v-model="adminForm.roles">
          <el-checkbox
            v-for="role in roleList"
            :key="role.id"
            :label="role.id"
            :disabled="role.status !== 1"
          >{{ role.role_name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="Name" prop="real_name">
        <el-input v-model="adminForm.real_name"></el-input>
      </el-form-item>
      <el-form-item label="Status" prop="status">
        <el-switch v-model="adminForm.status" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item v-show="false">
        <el-button native-type="submit">Submit</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :loading="isSubmitting" @click="handleSubmit">Submit</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, nextTick, computed } from 'vue'
import { getAdminInfo, insertAdmin, updateAdmin } from '@/api/admin'
import { getRoleList } from '@/api/role'

// 1. define props
interface PropsType {
  id: number | null
}

const props = defineProps<PropsType>()

// 2. initialize form
const adminForm = ref<AdminFormType>({
  account: '',
  pwd: '',
  conf_pwd: '',
  real_name: '',
  roles: [],
  status: 0,
})

const adminFormRules = computed(() => ({
  account: [
    {
      required: true,
      message: 'Please input account',
      trigger: 'change',
    },
  ],
  pwd: [
    {
      required: props.id === null,
      message: 'Please input password',
      trigger: 'change',
    },
  ],
  conf_pwd: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== adminForm.value.pwd) {
          callback(new Error('The two passwords that you entered do not match!'))
        } else {
          callback()
        }
      },
    },
  ],
  roles: [
    {
      type: 'array',
      required: true,
      message: 'Please select role',
    }
  ]
}))

const isLoadingAdminInfo = ref(false)

watch(
  () => props.id,
  () => {
    if (props.id) {
      isLoadingAdminInfo.value = true

      getAdminInfo(props.id).then(res => {

        res.roles = res.roles.map(role => +role) // 字符串转数字

        adminForm.value = res

      }).finally(() => {
        isLoadingAdminInfo.value = false
      })
    }
  },
  {
    immediate: true
  }
)

// 3. get role list
const roleList = ref([] as RoleType[])

function handleGetRoleList() {
  getRoleList().then(res => {
    roleList.value = res.list
  })
}

handleGetRoleList()

// 4. submit form
const isSubmitting = ref(false)

const emits = defineEmits(['update:modelValue', 'update:id', 'submit'])

const formEle = ref(null) as any

function handleSubmit() {
  formEle.value.validate().then(() => {
    isSubmitting.value = true

    const id = props.id

    const request = id ? updateAdmin(id, adminForm.value) : insertAdmin(adminForm.value)

    request.then(() => {
      onClose()
      emits('submit')
    }).finally(() => {
      isSubmitting.value = false
    })
  })
}

// 5. clear form
function onClose(done: Function = () => { }) {
  formEle.value.resetFields()
  nextTick(() => {
    formEle.value.clearValidate()
    emits('update:modelValue', false)
    emits('update:id', null)
    done()
  })
}
</script>
